package com.xuecheng.teaching.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.jdbc.TimeUtil;
import com.xuecheng.commons.constants.CommentContants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.Comment2Dto;
import com.xuecheng.commons.model.dto.CommentDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.api.ContentClient;
import com.xuecheng.system.api.SystemApi;
import com.xuecheng.system.domain.User;
import com.xuecheng.teaching.domain.Comment;
import com.xuecheng.teaching.domain.CommentReply;
import com.xuecheng.teaching.mapper.CommentMapper;
import com.xuecheng.teaching.service.CommentReplyService;
import com.xuecheng.teaching.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-08-13
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private CommentReplyService commentReplyService;

    //课程评论列表
    @Override
    public ResponseResult commentList(PageRequest request, Comment2Dto dto) {
        // 构建分页
        Page<Comment> page = new Page<>(request.getPageNo(), request.getPageSize());
        // 2.构建条件
        LambdaQueryWrapper<Comment> qw = new LambdaQueryWrapper<>();
        qw.eq(dto.getTargetId() != null, Comment::getTargetId, dto.getTargetId());
        qw.eq(dto.getLevel() != null, Comment::getLevel, dto.getLevel());
        //查父表
        page = this.page(page, qw);

        List<Comment> records = page.getRecords();
        //补充数据
        //自定义子类集合，存数据
        List<CommentVo> voList = new ArrayList<>();
        //遍历，分页评论
        for (Comment record : records) {
            // 存入vo
            CommentVo vo = BeanHelper.copyProperties(record, CommentVo.class);
            vo.setCommentId(record.getId().intValue());
            vo.setForbidReply(record.getForbidReply());
            // 判断是否存在回复
            if (vo.getForbidReply() == 1) {
                // 不存在
                voList.add(vo);
            } else {
                Long id = record.getId();
                //查子表
                LambdaQueryWrapper<CommentReply> qw1 = new LambdaQueryWrapper<>();
                qw1.eq(CommentReply::getCommentId, id);
                List<CommentReply> list = commentReplyService.list(qw1);
                // 判断是否有回复
                if (CollectionUtil.isNotEmpty(list)) {
                    vo.setReplyDTOList(list.toArray());
                }
                voList.add(vo);
            }


        }


        return PageResponseResult.okResult(page.getTotal(), voList);

        /*
            1.
         */
    }

    //课程评论统计
    @Override
    public ResponseResult countById(Long targetId) {
        // 通过 id 查
        LambdaQueryWrapper<Comment> qw = new LambdaQueryWrapper<>();
        qw.eq(Comment::getTargetId, targetId);
        List<Comment> commentList = this.list(qw);
        // 获取长度
        int total = commentList.size();
        int starRank = 0;
        int starRank1 = 0;
        int starRank2 = 0;
        int starRank3 = 0;
        int starRank4 = 0;
        int starRank5 = 0;
        //  获取星级
        for (Comment comment : commentList) {
            switch (comment.getStarRank()) {
                case 1:
                    starRank1++;
                    break;
                case 2:
                    starRank2++;
                    break;
                case 3:
                    starRank3++;
                    break;
                case 4:
                    starRank4++;
                    break;
                case 5:
                    starRank5++;
                    break;
            }

        }

        //  封装 vo
        CountVo vo = new CountVo();
        vo.setStarRank1Nums(starRank1);
        vo.setStarRank2Nums(starRank2);
        vo.setStarRank3Nums(starRank3);
        vo.setStarRank4Nums(starRank4);
        vo.setStarRank5Nums(starRank5);
        vo.setTargetId(targetId);
        vo.setTotalCommentNums(total);

        if (total == 0) {
            total = 1;
        }

        starRank = (starRank1 + starRank2 * 2 + starRank3 * 3 + starRank4 * 4 + starRank5 * 5) / total;
        vo.setStarRank(String.valueOf(starRank));

        return ResponseResult.okResult(vo);

    }

    @Autowired
    private ContentClient contentClient;

    @Autowired
    private SystemApi systemApi;

    // 评论课程
    @Override
    public ResponseResult commentPub(CommentDto dto) {
        Long userId = AuthInfoHolder.getUserId();
        Long companyId = AuthInfoHolder.getCompanyId();
        // 远程调用 system 获取 usernname
        ResponseResult<User> uerInfo = systemApi.uerInfo(userId);
        String userName = uerInfo.getData().getName();
        // 获取星级
        Integer starRank = dto.getStarRank();
        // 获取 id
        Integer targetId = dto.getTargetId();
        // 远程调用 content 通过 课程id  获得 课程名字
        ResponseResult<CoursePubVo> responseResult = contentClient.findById(targetId.longValue());
        CoursePubVo pubVo = responseResult.getData();
        String targrtName = pubVo.getName();
        //封装
        Comment comment = new Comment();
        comment.setUserId(userId);   // 用户 id
        comment.setUserName(userName);   // 用户姓名
        comment.setNickName(userName);    //  nick 名字
        comment.setTargetId(targetId.longValue());   // 课程 id
        comment.setStarRank(starRank);   //  星级
        comment.setCommentText(dto.getCommentText());   // 评论内容
        comment.setComeFrom(targetId.toString());    //  来源项目
        comment.setCommentDate(new Date());     // 创建时间
        comment.setStatus(1);     //  评论 显示
        comment.setTargetName(targrtName);  // 课程名字
        comment.setBelongTo(companyId);   // 属于

        //  通过星级 判断 好评
        if (starRank > 0 && starRank < 3) {
            comment.setLevel(-1);
        } else if (starRank == 3 && starRank < 4) {
            comment.setLevel(0);
        } else if (starRank >= 4 && starRank <= 5) {
            comment.setLevel(1);
        }
        this.save(comment);
        // entiy -> vo
        CommentVo vo = BeanHelper.copyProperties(comment, CommentVo.class);


        return ResponseResult.okResult(vo);
    }

    //机构的评论列表
    @Override
    public ResponseResult listAll(PageRequest request) {

        // 构建分页
        Page<Comment> page = new Page<>(request.getPageNo(), request.getPageSize());
        // 2.构建条件
        LambdaQueryWrapper<Comment> qw = new LambdaQueryWrapper<>();
        //查父表
        page = this.page(page, qw);

        List<Comment> records = page.getRecords();
        //补充数据
        //自定义子类集合，存数据
        List<CommentVo> voList = new ArrayList<>();
        //遍历，分页评论
        for (Comment record : records) {
            // 存入vo
            CommentVo vo = BeanHelper.copyProperties(record, CommentVo.class);
            vo.setCommentId(record.getId().intValue());
            vo.setUserName(record.getUserName());
            Long id = record.getId();
            //查子表
            LambdaQueryWrapper<CommentReply> qw1 = new LambdaQueryWrapper<>();
            qw1.eq(ObjectUtil.isNotEmpty(id), CommentReply::getCommentId, id);
            List<CommentReply> list = commentReplyService.list(qw1);
            // 判断是否有回复
            if (CollectionUtil.isNotEmpty(list)) {
                vo.setReplyDTOList(list.toArray());
            }
            voList.add(vo);
            // }
        }
        return PageResponseResult.okResult(page.getTotal(), voList);
    }

    // 机构模糊查询
    @Override
    public ResponseResult getLike(String courseName) {
        PageRequest pageRequest = new PageRequest();
        Integer pageNo = pageRequest.getPageNo();
        Integer pageSize = pageRequest.getPageSize();
        // 构建分页
        Page<Comment> page = new Page<>(pageNo, pageSize);
        // 2.构建条件
        LambdaQueryWrapper<Comment> qw = new LambdaQueryWrapper<>();
        qw.like(StrUtil.isNotBlank(courseName), Comment::getTargetName, courseName);
        //查父表
        page = this.page(page, qw);

        List<Comment> records = page.getRecords();
        //补充数据
        //自定义子类集合，存数据
        List<CommentVo> voList = new ArrayList<>();
        //遍历，分页评论
        for (Comment record : records) {
            // 存入vo
            CommentVo vo = BeanHelper.copyProperties(record, CommentVo.class);
            vo.setCommentId(record.getId().intValue());
            vo.setForbidReply(record.getForbidReply());
            // 判断是否存在回复
            if (vo.getForbidReply() == 1) {
                // 不存在
                voList.add(vo);
            } else {
                Long id = record.getId();
                //查子表
                LambdaQueryWrapper<CommentReply> qw1 = new LambdaQueryWrapper<>();
                qw1.eq(CommentReply::getCommentId, id);
                List<CommentReply> list = commentReplyService.list(qw1);
                // 判断是否有回复
                if (CollectionUtil.isNotEmpty(list)) {
                    vo.setReplyDTOList(list.toArray());
                }
                voList.add(vo);
            }
        }
        return PageResponseResult.okResult(page.getTotal(), voList);

    }
}
